package cn.itcast.shiro;

import cn.itcast.dao.user.UserDao;
import cn.itcast.domain.Module;
import cn.itcast.domain.User;
import cn.itcast.service.module.ModuleService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class AuthRealm extends AuthorizingRealm {

    @Autowired
    private UserDao userDao;

    @Autowired
    private ModuleService moduleService;


    @Override  //授权
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {

        System.out.println("执行到配置文件中:/system/module/list.do=perms['模块管理']会来该方法中查询登录用户的具备权限");

        //认证
            //方法参数：是安全数据的集合
            User user =(User)principalCollection.getPrimaryPrincipal();
            List<Module> list = moduleService.findMenus(user);
            Set<String> set = new HashSet<>();
            for (Module module : list) {
                set.add(module.getName());
            }
            System.out.println("该认证用户具备的权限:"+set);
        //返回参数：是权限集合
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        simpleAuthorizationInfo.setStringPermissions(set);
        return simpleAuthorizationInfo; //没有任何权限
    }

    @Override //认证
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {

        // 根据email获取到数据库的安全数据（User对象）
        UsernamePasswordToken uptoken=(UsernamePasswordToken)authenticationToken;
        String email = uptoken.getUsername();
        User user = userDao.findByUser(email);
        if(user==null){
            return null; //null--shiro-->抛异常
        }
        //user不为空的情况下调用密码比较器
                            //给密码比较器传递的参数
                            //参数1：数据库查询出来的安全数据对象
                            //参数2：数据库安全数据对象的密码证书
                            //参数3：当前AuthRealm的名称
        return new SimpleAuthenticationInfo(user,user.getPassword(),this.getName());
    }
}
